package action

import (
	"html/template"
	"net/http"
	"time"
)

type client struct {
	ID     string
	Time   int64
	Topics []string
}

//将unix时间戳转为字符串，函模板内调用
func TimeToStr(t int64) string {
	return time.Unix(t, 0).Format("2006-01-02 15:04:05")
}

func (dispatcher *Dispatcher) Status(w http.ResponseWriter, r *http.Request) {
	data := make(map[string]interface{})
	clients := make(map[string]*client)
	//遍历客户端池，只取出ID和Time属性值，以便模板上读取
	for k := range dispatcher.Clients {
		clients[k.id] = &client{
			ID:     k.id,
			Time:   k.time,
			Topics: k.topics,
		}
		//log.Println(k)
	}
	data["clients"] = clients
	data["TimeToStr"] = TimeToStr
	data["clientCount"] = len(clients)
	//以即时渲染的方式执行模板
	if err := template.Must(template.ParseFiles("templates/status.html")).Execute(w, data); err != nil {
		w.Write([]byte(err.Error()))
		return
	}
}
